import myAxios from "../plugins/MyAxios.ts";
import { setCurrentUserStatus, getCurrentUserStatus } from "../states/user.ts";

/**
 * 获取当前用户信息
 * @returns Promise<UserType | null> 用户信息或null
 */
export const getCurrentUser = async (): Promise<UserType | null> => {
  try {
    // 先检查本地缓存
    const cachedUser = getCurrentUserStatus();
    if (cachedUser) {
      return cachedUser;
    }

    // 从服务器获取用户信息
    const res = await myAxios.get('/user/current');
    
    if (res.status === 0 && res.data) {
      setCurrentUserStatus(res.data);
      return res.data;
    }
    
    return null;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

/**
 * 检查用户是否已登录
 * @returns boolean
 */
export const isUserLoggedIn = (): boolean => {
  const user = getCurrentUserStatus();
  return !!user;
};

/**
 * 清除用户登录状态
 */
export const clearUserStatus = (): void => {
  setCurrentUserStatus(null as any);
};